package com.elf.zero.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

import com.elf.zero.utils.LogUtils;

/**
 * 有状态的scrollView
 */
public class StatefulScrollView extends ScrollView {

    private boolean scroll;
    private OnScrollStateListener mOnScrollStateListener;
    private Handler scrollHandler;
    private int lastY;
    private boolean touchUp;

    private final Object lock = new Object();

    public StatefulScrollView(Context context) {
        this(context, null);
    }

    public StatefulScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        scrollHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                synchronized (lock) {
                    LogUtils.v("scrollHandler", "lastY = " + lastY);
                    LogUtils.v("scrollHandler", "getScrollY = " + getScrollY());

                    if (scroll && touchUp && lastY == getScrollY()) {
                        //停止了，此处你的操作业务
                        scroll = false;
                        lastY = 0;
                        if (mOnScrollStateListener != null) {
                            mOnScrollStateListener.onScrollStateChanged(StatefulScrollView.this, OnScrollStateListener.SCROLL_STATE_IDLE);
                        }
                    } else {
                        scrollHandler.sendEmptyMessageDelayed(1, 20);
                        lastY = getScrollY();
                    }
                    return false;
                }
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            touchUp = false;
        } else if (ev.getAction() == MotionEvent.ACTION_UP) {
            touchUp = true;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        synchronized (lock) {
            if (!scroll) {
                scroll = true;
                lastY = 0;
                if (mOnScrollStateListener != null) {
                    mOnScrollStateListener.onScrollStateChanged(this, OnScrollStateListener.SCROLL_STATE_SCROLL);
                }
                scrollHandler.sendEmptyMessage(1);
            }
        }
    }

    public void setOnScrollStateListener(OnScrollStateListener listener) {
        mOnScrollStateListener = listener;
    }

    public interface OnScrollStateListener {
        int SCROLL_STATE_IDLE = 0;
        int SCROLL_STATE_SCROLL = 1;

        void onScrollStateChanged(ScrollView view, int scrollState);
    }
}
